package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyComment;
import cn.wolfcode.trip.base.domain.Tag;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.StrategyCommentMapper;
import cn.wolfcode.trip.base.mapper.TagMapper;
import cn.wolfcode.trip.base.query.StrategyCommentQueryObject;
import cn.wolfcode.trip.base.service.IStrategyCommentService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 攻略评论服务层实现类
 *
 * @author totoro93
 * @date 2019-01-14
 **/
@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentMapper strategyCommentMapper;
    @Autowired
    private TagMapper tagMapper;

    @Override
    public PageInfo query(StrategyCommentQueryObject queryObject) {
        PageHelper.startPage(queryObject.getCurrentPage(), queryObject.getPageSize(), queryObject.getOrderBy());
        List<StrategyComment> list = strategyCommentMapper.selectForList(queryObject);
        return new PageInfo(list);
    }

    @Override
    public void save(StrategyComment strategyComment, String[] tags) {
        //保存当前用户信息
        User user = new User();
        System.out.println(UserContext.getCurrentUser());
        user.setId((Long) UserContext.getCurrentUser().get("id"));
        strategyComment.setUser(user);
        //保存评论
        strategyCommentMapper.insert(strategyComment);
        //判断标签是否有值，逐个保存，并保存评论和标签关系中间对应表
        if (tags.length > 0) {
            for (String tagName : tags) {
                //判断标签库是否已存在标签，存在则直接拿出id用于保存中间表
                Tag tag = tagMapper.selectTagByName(tagName);
                if (tag == null) {
                    tag = new Tag();
                    tag.setName(tagName);
                    tagMapper.insert(tag);
                }
                //保存中间关系
                strategyCommentMapper.insertRelation(strategyComment.getId(), tag.getId());
            }
        }
    }
}
